package com.txzt.gaea.provide.service.impl;


import com.txzt.base.core.RtnInfo;
import com.txzt.gaea.common.base.service.impl.BaseServiceImpl;
import com.txzt.gaea.common.core.base.context.AdminUserContext;
import com.txzt.gaea.common.page.PageInfoBT;
import com.txzt.gaea.provide.dto.InformationTypeInfoAddDTO;
import com.txzt.gaea.provide.dto.InformationTypeInfoUpdateDTO;
import com.txzt.gaea.provide.dto.InformationTypeQueryDTO;
import com.txzt.gaea.provide.model.InformationTypeInfo;
import com.txzt.gaea.provide.service.InformationTypeInfoService;
import com.txzt.gaea.provide.service.biz.AdminUserApiService;
import com.txzt.gaea.provide.utils.BeanConvertUtils;
import com.txzt.gaea.provide.vo.InformationTypeInfoVO;
import com.txzt.gaea.vo.AdminUserVO;
import com.txzt.gaea.vo.UserDetailVO;
import io.lettuce.core.internal.LettuceLists;
import lombok.extern.log4j.Log4j2;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;


@Service
@Log4j2
public class InformationTypeInfoServiceImpl extends BaseServiceImpl<InformationTypeInfo> implements InformationTypeInfoService {

    @Autowired
    private AdminUserApiService adminUserApiService;

    @Override
    public RtnInfo<PageInfoBT<InformationTypeInfoVO>> list(InformationTypeQueryDTO dto) throws Exception {
        PageQuery<InformationTypeInfo> pageQuery = new PageQuery<>(dto.getPageNumber(), dto.getPageSize(), dto);
        PageQuery<InformationTypeInfo> result = this.sqlManager.pageQuery("informationTypeInfo.queryByCondition", InformationTypeInfo.class, pageQuery);
        //为空直接返回
        if (CollectionUtils.isEmpty(result.getList())) {
            return RtnInfo.success(new PageInfoBT(result));
        }
        List<InformationTypeInfoVO> vos = new ArrayList<>();
        List<Long> userIds = new ArrayList<>();
        for (InformationTypeInfo InformationTypeInfo : result.getList()) {
            InformationTypeInfoVO vo = BeanConvertUtils.convertTo(InformationTypeInfo, InformationTypeInfoVO::new, (s, t) -> {

            });
            userIds.add(InformationTypeInfo.getCreateBy());
            vos.add(vo);
        }
        Map<Long, UserDetailVO> userDetailMap = adminUserApiService.getUserDetailVos(userIds);
        if (!CollectionUtils.isEmpty(userDetailMap)) {
            for (InformationTypeInfoVO vo : vos) {
                if (!userDetailMap.containsKey(vo.getCreateBy())) {
                    log.error("门户没有查到发布者ID, 文件ID：{}， 发布者ID:{}", vo.getId(), vo.getCreateBy());
                    continue;
                }
                UserDetailVO userDetailVO = userDetailMap.get(vo.getCreateBy());
                vo.setCreateByName(userDetailVO.getName());
                vo.setBelongDeptName(userDetailVO.getDeptVO().getSimplename());
            }
        }
        result.setList(vos);
        return RtnInfo.success(new PageInfoBT(result));
    }

    @Override
    public RtnInfo add(InformationTypeInfoAddDTO dto) throws Exception {
        AdminUserVO adminUserVO = AdminUserContext.getUser();
        if (null == adminUserVO) {
            return RtnInfo.error(500, "当前用户已过期，请重新登录。");
        }
        Date time = new Date();
        InformationTypeInfo informationTypeInfo = BeanConvertUtils.convertTo(dto, InformationTypeInfo::new, (s, t) -> {
            t.setCreateTime(time);
            t.setCreateBy(adminUserVO.getId());
            t.setIsDelete(0);
        });
        int count = this.save(informationTypeInfo);
        if (count <= 0) {
            return RtnInfo.SERVER_ERROR;
        }
        return RtnInfo.SUCCESS;
    }

    @Override
    public RtnInfo detail(Long id) throws Exception {
        InformationTypeInfo informationTypeInfo = this.selectById(id);
        InformationTypeInfoVO vo = BeanConvertUtils.convertTo(informationTypeInfo, InformationTypeInfoVO::new, (s, t) -> {

        });
        Map<Long, UserDetailVO> userDetailMap = adminUserApiService.getUserDetailVos(LettuceLists.newList(vo.getCreateBy()));
        if (!CollectionUtils.isEmpty(userDetailMap)) {
            if (!userDetailMap.containsKey(vo.getCreateBy())) {
                log.error("门户没有查到发布者ID, 文件ID：{}， 发布者ID:{}", vo.getId(), vo.getCreateBy());
                return RtnInfo.success(vo);
            }
            UserDetailVO userDetailVO = userDetailMap.get(vo.getCreateBy());
            vo.setCreateByName(userDetailVO.getName());
            vo.setBelongDeptName(userDetailVO.getDeptVO().getSimplename());
        }
        return RtnInfo.success(vo);
    }

    @Override
    public RtnInfo update(InformationTypeInfoUpdateDTO dto) throws Exception {
        AdminUserVO adminUserVO = AdminUserContext.getUser();
        if (null == adminUserVO) {
            return RtnInfo.error(500, "当前用户已过期，请重新登录。");
        }
        if (dto.getId() == 1 || dto.getId() == 2 || dto.getId() == 3) {
            return RtnInfo.error(501, "初始化类型，不能修改");
        }
        InformationTypeInfo dataDb = this.selectById(dto.getId());
        if (null == dataDb || !Objects.equals(dataDb.getCreateBy(), adminUserVO.getId())){
            return RtnInfo.error(502, "您无权修改，只有创建者可以编辑类目");
        }
        Date time = new Date();
        InformationTypeInfo informationTypeInfo = BeanConvertUtils.convertTo(dto, InformationTypeInfo::new, (s, t) -> {
            t.setUpdateBy(adminUserVO.getId());
            t.setUpdateTime(time);
        });
        int count = this.sqlManager.update("informationTypeInfo.updateInfoById", informationTypeInfo);
        if (count <= 0) {
            return RtnInfo.SERVER_ERROR;
        }
        return RtnInfo.SUCCESS;
    }

    @Override
    public RtnInfo del(Long id) {
        AdminUserVO adminUserVO = AdminUserContext.getUser();
        if (null == adminUserVO) {
            return RtnInfo.error(500, "当前用户已过期，请重新登录。");
        }
        if (id == 1 || id == 2 || id == 3) {
            return RtnInfo.error(501, "初始化类型，不能删除");
        }
        InformationTypeInfo dataDb = this.selectById(id);
        if (null == dataDb || !Objects.equals(dataDb.getCreateBy(), adminUserVO.getId())){
            return RtnInfo.error(502, "您无权删除，只有创建者可以删除类目");
        }
        InformationTypeInfo informationTypeInfo = InformationTypeInfo.builder().id(id).updateBy(adminUserVO.getId()).
                updateTime(new Date()).isDelete(1).build();
        int count = this.sqlManager.update("informationTypeInfo.updateInfoById", informationTypeInfo);
        if (count <= 0) {
            log.error("删除数据失败。id:{}", id);
            return RtnInfo.SERVER_ERROR;
        }
        return RtnInfo.SUCCESS;
    }
}
